package controller.notice;

import base.response.OffsetLimitPage;
import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import controller.common.BaseController;
import controller.common.StaticConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import properties.SystemProperty;
import response.CommonResult;
import services.expertInfo.ExpertBaseServices;
import services.notice.NoticeAccountServices;
import services.notice.NoticeInfoServices;
import services.notice.NoticeRoleServices;
import services.upms.AccountServices;
import services.upms.RoleServices;
import util.JsonUtil;
import util.io.FtpUtil;
import util.io.PoiExcelReadUtil;
import util.key.IDFactory;
import validator.NotBlankFluentValidator;
import validator.NotNullFluentValidator;
import wt.entity.expertInfo.ExpertBase;
import wt.entity.expertInfo.ExpertBaseExample;
import wt.entity.notice.*;
import wt.entity.upms.Account;
import wt.entity.upms.AccountExample;
import wt.entity.upms.Role;
import wt.entity.upms.RoleExample;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 功能:
 * 作者: 洪世成
 * 日期: 2017/9/9
 * 版权所有: admin
 */
@Controller
@RequestMapping("notice/noticeInfoManager")
public class NoticeInfoManagerController extends BaseController {
    @Autowired
    NoticeInfoServices noticeInfoServices;
    @Autowired
    NoticeRoleServices noticeRoleServices;
    @Autowired
    NoticeAccountServices noticeAccountServices;

    @Autowired
    RoleServices roleServices;

    @Autowired
    ExpertBaseServices expertBaseServices;
    @Autowired
    AccountServices accountServices;

    @RequiresPermissions("notice:noticeInfoManager:default")
    @RequestMapping("index")
    public String index() {
        return "notice/noticeInfoManager/index";
    }

    @RequiresPermissions("notice:noticeInfoManager:default")
    @RequestMapping("editDlg")
    public String editDlg(Map map) throws Exception {

        map.put("roleList", roleServices.selectByExample(null));
        map.put(StaticConstant.EDIT_URL, "notice/noticeInfoManager/insert");
        map.put(StaticConstant.EDIT_OPERATE_TYPE, StaticConstant.EDIT_INSERT);

        return "notice/noticeInfoManager/editDlg";
    }

    @RequiresPermissions("notice:noticeInfoManager:default")
    @ResponseBody
    @RequestMapping(value = "insert")
    public CommonResult insert(NoticeInfo noticeInfo,
                               @RequestParam(value = "roles[]", required = false) List<String> roleIdList,
                               MultipartFile expertFile,
                               MultipartFile extendFile
    ) throws Exception {
        CommonResult commonResult = CommonResult.newCommonResult();
        ComplexResult result;
        if ("generalAnnouncement".equals(noticeInfo.getNoticeType())) {//一般公告

            result = FluentValidator.checkAll().failOver()
                    .on(noticeInfo.getName(), new NotBlankFluentValidator("标题"))
                    .on(noticeInfo.getName(), new NotBlankFluentValidator("发布内容"))
                    .on((roleIdList == null || roleIdList.isEmpty()) ? null : true, new NotNullFluentValidator("发布对象"))
                    .doValidate()
                    .result(ResultCollectors.toComplex());
            noticeInfo.setAddress(null);
            noticeInfo.setStartTime(null);
            noticeInfo.setEndTime(null);
        } else {

            if ("generalNotice".equals(noticeInfo.getNoticeType())) {//一般通知
                result = FluentValidator.checkAll().failOver()
                        .on(noticeInfo.getName(), new NotBlankFluentValidator("标题"))
                        .on(noticeInfo.getName(), new NotBlankFluentValidator("发布内容"))
                        .on(expertFile.getSize() == 0 ? null : true, new NotNullFluentValidator("发布对象"))
                        .doValidate()
                        .result(ResultCollectors.toComplex());

                noticeInfo.setAddress(null);
                noticeInfo.setStartTime(null);
                noticeInfo.setEndTime(null);


            } else if ("trainingNotice".equals(noticeInfo.getNoticeType())) {//培训通知

                result = FluentValidator.checkAll().failOver()
                        .on(noticeInfo.getName(), new NotBlankFluentValidator("标题"))
                        .on(noticeInfo.getName(), new NotBlankFluentValidator("发布内容"))
                        .on(noticeInfo.getAddress(), new NotBlankFluentValidator("培训地址"))
                        .on(noticeInfo.getStartTime(), new NotNullFluentValidator("开始时间"))
                        .on(noticeInfo.getEndTime(), new NotNullFluentValidator("结束时间"))
                        .on(expertFile.getSize() == 0 ? null : true, new NotNullFluentValidator("发布对象"))
                        .doValidate()
                        .result(ResultCollectors.toComplex());

            } else {
                commonResult.setMessage("类型异常");
                return commonResult.setError();
            }


        }

        if (!result.isSuccess()) {
            commonResult.addMessage(result);
            return commonResult.setError();
        }


        String fileName = extendFile.getOriginalFilename();
        String savePath = SystemProperty.getNoticeFileFolder() + "/";
        String newFileName = IDFactory.getSnowflakeId() + "." + fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();


        noticeInfo.setReleaseTime(new Date());
        noticeInfo.setAccountId(getLoginAccount().getId());
        noticeInfo.setAccountName(getLoginAccount().getStaffInfo().getName());
        noticeInfo.setFileName(fileName);
        noticeInfo.setFileSrc("downloadFileByPath?pathName=" + savePath + newFileName);


        if ("generalAnnouncement".equals(noticeInfo.getNoticeType())) {
            if (extendFile.getSize() > 0) {
                boolean r = FtpUtil.saveFileByRelativePath(extendFile.getInputStream(), savePath, newFileName);
                if (!r) {
                    commonResult.addMessage("附件存储失败");
                    return commonResult.setError();
                }
            }
            noticeInfoServices.insertSelectiveAnnouncement(noticeInfo, roleIdList);
        } else {
            List<String[]> list;
            try {
                list = PoiExcelReadUtil.readExcel(expertFile.getInputStream(), 2, 0, 2, 0);
            } catch (Exception e) {
                e.printStackTrace();
                commonResult.addMessage("发布对象excel读取失败");
                return commonResult.setError();
            }
            if (list.size() == 0) {
                commonResult.addMessage("发布对象excel 内容不能为空");
                return commonResult.setError();
            }


            List<String> accountIdList = new ArrayList<String>();
            for (String[] strings : list) {
                ExpertBase expertBase = expertBaseServices.selectByIdCard(strings[1]);
                if (expertBase == null) {
                    commonResult.addMessage(strings[0] + " " + strings[1] + "不存在");
                } else {
                    AccountExample accountExample = new AccountExample();
                    accountExample.createCriteria().andExpertIdEqualTo(expertBase.getId());
                    List<Account> accountList = accountServices.selectByExample(accountExample);
                    if (accountList.isEmpty()) {
                        commonResult.addMessage(strings[0] + " " + strings[1] + " 还未激活账户");
                    } else {
                        accountIdList.add(accountList.get(0).getId());
                    }
                }
            }


            if (accountIdList.size() != list.size()) {
                return commonResult.setError();
            }

            if (extendFile.getSize() > 0) {
                boolean r = FtpUtil.saveFileByRelativePath(extendFile.getInputStream(), savePath, newFileName);
                if (!r) {
                    commonResult.addMessage("附件存储失败");
                    return commonResult.setError();
                }
            }

            noticeInfoServices.insertSelectiveNotice(noticeInfo, accountIdList);

        }

        return commonResult.setSuccess();
    }

    @RequiresPermissions("notice:noticeInfoManager:default")
    @ResponseBody
    @RequestMapping("select")
    public OffsetLimitPage select(NoticeInfo noticeInfo, Integer limit, Integer offset) throws Exception {
        NoticeInfoExample noticeInfoExample = new NoticeInfoExample();
        noticeInfoExample.setOrderByClause("id desc" );

        NoticeInfoExample.Criteria criteria = noticeInfoExample.createCriteria();
        if (noticeInfo.getStartTime() != null) {
            criteria.andReleaseTimeGreaterThanOrEqualTo(noticeInfo.getStartTime());
        }

        if (noticeInfo.getEndTime() != null) {
            criteria.andReleaseTimeLessThan(noticeInfo.getEndTime());
        }

        if (!StringUtils.isEmpty(noticeInfo.getNoticeType())) {
            criteria.andNoticeTypeEqualTo(noticeInfo.getNoticeType());
        }

        OffsetLimitPage offsetLimitPage = noticeInfoServices.selectByExample(noticeInfoExample, offset, limit);

        return offsetLimitPage;
    }




    @RequiresPermissions("notice:noticeInfoManager:default")
    @RequestMapping("publishObject")
    public String publishObject(String id, Map map) throws Exception {
        NoticeInfo noticeInfo = noticeInfoServices.selectByPrimaryKey(id);

        if ("generalAnnouncement".equals(noticeInfo.getNoticeType())) {

            NoticeRoleExample noticeRoleExample = new NoticeRoleExample();
            noticeRoleExample.createCriteria().andNoticeIdEqualTo(noticeInfo.getId());
            List<NoticeRole> noticeRoleList = noticeRoleServices.selectByExample(noticeRoleExample);
            List<String> roleIdList = new ArrayList<String>();
            for (NoticeRole noticeRole : noticeRoleList) {
                roleIdList.add(noticeRole.getRoleId());
            }

            RoleExample roleExample = new RoleExample();
            roleExample.createCriteria().andIdIn(roleIdList);
            List<Role> roleList = roleServices.selectByExample(roleExample);
            map.put("data",JsonUtil.obj2Json(roleList));
            map.put("type","role");

        } else {

            NoticeAccountExample noticeAccountExample = new NoticeAccountExample();
            noticeAccountExample.createCriteria().andNoticeIdEqualTo(noticeInfo.getId());
            List<NoticeAccount> noticeAccountList = noticeAccountServices.selectByExample(noticeAccountExample);

            List<String> accountIdList = new ArrayList<String>();
            for (NoticeAccount noticeAccount : noticeAccountList) {
                accountIdList.add(noticeAccount.getAccountId());
            }

            AccountExample accountExample = new AccountExample();
            accountExample.createCriteria().andIdIn(accountIdList);
            List<Account> accountList = accountServices.selectByExample(accountExample);


            List<String> expertIdList = new ArrayList<String>();

            for (Account account : accountList) {
                expertIdList.add(account.getExpertId());
            }

            ExpertBaseExample expertBaseExample = new ExpertBaseExample();
            expertBaseExample.createCriteria().andIdIn(expertIdList);
            List<ExpertBase> expertBaseList = expertBaseServices.selectByExample(expertBaseExample);
            map.put("data", JsonUtil.obj2Json(expertBaseList));
            map.put("type","expert");

        }

        return "notice/noticeInfoManager/publishObject";
    }



    @RequestMapping("detail")
    public String detail(String id, Map map) throws Exception {
        map.put("data", noticeInfoServices.selectByPrimaryKey(id));
        return "notice/noticeInfoManager/detail";
    }


}
